package com.xdja.netty.learn.websockets;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import java.util.List;

/**
 * description
 *
 * @author zk
 * @since 2018/7/24
 */
public class WebSocketsServer {
    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        ChannelFuture channelFuture = serverBootstrap.group(new NioEventLoopGroup(),new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline()
                                .addLast("httpServer",new HttpServerCodec())
                                .addLast("objAggregator",new HttpObjectAggregator(1024*512))
                                .addLast("webSocket", new WebSocketServerProtocolHandler("/ws"))
                                .addLast("text", new MessageToMessageDecoder<TextWebSocketFrame>() {
                                    @Override
                                    protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame msg, List<Object> out) throws Exception {
                                        System.out.println(msg.text());
                                    }
                                });
                    }
                }).bind(8989).sync();
        channelFuture.channel().closeFuture().sync();
    }
}
